package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.feign.BehaviorFeign;
import com.heima.article.mapper.ApCollectionMapper;
import com.heima.article.service.ApCollectionService;
import com.heima.model.article.dtos.CollectionBehaviorDto;
import com.heima.model.article.pojos.ApCollection;
import com.heima.model.behavior.dtos.BehaviorEntryDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @作者 itcast
 * @创建日期 2020/10/8 15:30
 **/
@Service
@Transactional
public class ApCollectionServiceImpl extends ServiceImpl<ApCollectionMapper, ApCollection> implements ApCollectionService {
    @Autowired
    BehaviorFeign behaviorFeign;
    @Override
    public ResponseResult collectionBehavior(CollectionBehaviorDto dto) {
        // 参数校验
        if(dto == null || dto.getArticleId() == null
                || (dto.getOperation()!= 0 && dto.getOperation()!=1)
                || (dto.getType() != 0 && dto.getType() != 1)
        ){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 获取行为实体
        ApUser user = AppThreadLocalUtils.getUser();
        ApBehaviorEntry behaviorEntry = behaviorFeign.findByUserIdOrEquipmentId(user.getId(),dto.getEquipmentId());
        if(behaviorEntry == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 查看是否收藏过
        ApCollection apCollection = getOne(Wrappers.<ApCollection>lambdaQuery()
                .eq(ApCollection::getArticleId, dto.getArticleId())
                .eq(ApCollection::getEntryId, behaviorEntry.getId()));
        // 收藏操作
        if(apCollection == null && dto.getOperation() == 0){ // 收藏
            apCollection = new ApCollection();
            apCollection.setArticleId(dto.getArticleId());
            apCollection.setCollectionTime(new Date());
            apCollection.setEntryId(behaviorEntry.getId());
            apCollection.setType(dto.getType());
            apCollection.setPublishedTime(dto.getPublishedTime());
            save(apCollection);
        }else if(apCollection != null && dto.getOperation() == 1){ // 取消收藏
            removeById(apCollection.getId());
        }
        return ResponseResult.okResult();
    }
}
